//
//  LS_ComposeViewController.swift
//  weibo
//
//  Created by 罗李苏 on 16/5/28.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class LS_ComposeViewController: UIViewController {
    //关闭按钮的点击事件
    @objc private func  close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //发送按钮的点击事件 发送文本型微博
    @objc private func send(){
        print("发送微博")
        LS_NetworkTools.sharedTools.sendStatus(textView.text,images: pictureSelector.images) { (responseObject, error) in
            if error != nil {
                 print(error ?? "")
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            
            //成功
            SVProgressHUD.showSuccessWithStatus("发布微博成功")

        }
    
    }
    
    @objc private func selectPicture() {
        print("选中图片")
        pictureSelector.view.snp_updateConstraints { (make) in
            make.height.equalTo(ScreenHeight / 3 * 2)
        }

    }
    
    @objc private func selectEmoticon() {
        print("选择表情")
    }

    override func viewDidLoad() {
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
        registerNotification()
    }
    //MARK:注册通知
    private func registerNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LS_ComposeViewController.keyBoardChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    }
    override func viewWillAppear(animated: Bool) {
        if pictureSelector.images.count == 0 {
            textView.becomeFirstResponder()
        }
    }
    //MARK:键盘的frame发生改变 toolBar 开始做动画
    @objc private func keyBoardChange(notify: NSNotification){
        //获取键盘隐藏或者显示的时间
        let time_t = (notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).doubleValue
        //结构体能够直接存放在字典中   --> 需要转换为 NSValue 才能存储
        let rect = (notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //获取键盘的frame
        let offset = -ScreenHeight + rect.origin.y
        //开启动画 改变toolBar的约束
        UIView.animateWithDuration(time_t) { 
            self.toolBar.snp_updateConstraints(closure: { (make) in
                make.bottom.equalTo(offset)
            })
            //提前刷新页面
            self.view.layoutIfNeeded()
        }
        
    }
    // MARK:懒加载创建右边item
    private lazy var rightbarButtonItem: UIBarButtonItem = {
        let btn = UIButton()
        //设置按钮显示文字
        btn.setTitle("发送", forState: .Normal)
        //添加点击事件
        btn.addTarget(self, action: #selector(LS_ComposeViewController.send), forControlEvents: .TouchUpInside)
        //设置文字颜色
        btn.setTitleColor(UIColor.orangeColor(), forState: .Disabled)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        //设置按钮上的文字大小
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        //设置frame
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        return barButtonItem
    }()
    
    //MARK:懒加载底部工具条
    private lazy var toolBar:UIToolbar = UIToolbar()
    //MARK:懒加载文本输入框
    private lazy var textView:UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        //设置滚动视图键盘消失的方式
        tv.keyboardDismissMode = .OnDrag
        tv.alwaysBounceVertical = true
        tv.delegate = self
        return tv
    }()
    //MARK:懒加载占位label
    private lazy var placeHolderLabel: UILabel = UILabel(title: "专治各种不服", font: 18, textColor: UIColor.lightGrayColor())
    //MARK:懒加载选择图片的控制器
    private lazy var pictureSelector:LS_PictureSelectorController = LS_PictureSelectorController()
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}
//MARK:textView的代理方法
extension LS_ComposeViewController: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        rightbarButtonItem.enabled = textView.hasText()
    }

}
//MARK:UI界面搭建
extension LS_ComposeViewController{
    
    private func setupUI(){
    setNavBar()
    setTextView()
    setToolBar()
    setSelectorVC()
    }
    //MARK:设置底部的工具条
    private func setToolBar(){
    //把底部工具条添加到父视图
    self.view.addSubview(toolBar)
    //设置约束
    toolBar.snp_makeConstraints { (make) in
        make.left.right.bottom.equalTo(self.view)
        }
        //定义数组存放创建的item
        var items = [UIBarButtonItem]()
        //操作数据 添加UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectPicture"]]
     //根据字典数据创建item
        for item in itemSettings {
            let imageName = item["imageName"]
            let action = item["actionName"]!
            //添加自定义的tabbBarButtonItem
            let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action), title: nil)
            items.append(item)
            //添加可伸缩弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
         }
        //移除最后一个弹簧
        items.removeLast()
        toolBar.items = items
    }
    //MARK:设置导航条
    private func setNavBar(){
        //MARK:设置左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "", target: self, action: #selector(LS_ComposeViewController.close), title: "关闭")
        //MARK:设置右边按钮
        navigationItem.rightBarButtonItem = rightbarButtonItem
        //设置右边按钮不可交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        //MARK:设置导航条的自定义视图
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        let titleLabel = UILabel(title: "发布微博", font: 16, textColor: UIColor.darkGrayColor())
        let nameaLbel = UILabel(title: LS_UserAccountViewModel.sharedAccountViewModel.userAccount?.name ?? "", font: 13, textColor: UIColor.darkGrayColor())
        myView.addSubview(titleLabel)
        myView.addSubview(nameaLbel)
        //添加约束
        titleLabel.snp_makeConstraints { (make) in
            make.top.equalTo(myView.snp_top)
            make.centerX.equalTo(myView.snp_centerX)
        }
        nameaLbel.snp_makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp_bottom)
            make.centerX.equalTo(myView.snp_centerX)
        }
        //赋值操作
        navigationItem.titleView = myView
        }
    //MARK:设置文本输入框
    private func setTextView(){
        self.view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3)
        }
        textView.addSubview(placeHolderLabel)
        
        placeHolderLabel.snp_makeConstraints { (make) in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
        
    }
    //MARK:设置图片选择器
    private func setSelectorVC(){
        //添加子控制器
        addChildViewController(pictureSelector)
        //使用子控制器的 View
        self.view.addSubview(pictureSelector.view)
        //把toolBar移动到最上层
        self.view.bringSubviewToFront(toolBar)
        //添加约束
        pictureSelector.view.snp_makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(0)
        }
        
    }
}
